<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>结算页面</title>
    <link rel="stylesheet" href="css/bootstrap.min.css" />
    <link rel="stylesheet" href="css/font-awesome.min.css" />
    <!--    Lobibox.css-->
    <link rel="stylesheet" href="css/Lobibox.min.css" />

    <script src="js/vue.js"></script>
    <script src="js/jquery.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
    <script src="js/jquery.cookie.min.js"></script>
    <script src="js/login-status.js"></script>
    <!--    Lobibox.js-->
    <script src="js/Lobibox.js"></script>

    <style>
        h4.title {
            font-weight: 800;
        }
        .mgl30 {
            margin-left: 30px;
        }
        #allAddressTable a {
            display: none;
        }
        /** 当鼠标划到 tr上的时候，让它下面的 a标签展示 */
        #allAddressTable tr:hover a{
            display: inline-block;
        }

    </style>
</head>
<body>
<%--导航栏--%>
<nav class="navbar navbar-default navbar-inverse navbar-static-top">
    <div class="container-fluid">
        <div class="navbar-header">
            <a href="index.jsp" class="navbar-brand" style="color: #ffffff;"><i class="fa fa-sign-language"></i> 寻欢易购</a>
        </div>

        <ul class="nav navbar-nav navbar-right">
            <li><a href="cart.jsp">购物车</a></li>
            <li><a href="showOrder.jsp">我的订单</a></li>
            <li id="li_register"><a href="register.jsp">注册</a></li>
            <li id="li_login"><a href="login.jsp">登录</a></li>
            <li id="li_user_info" class="dropdown">

                <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true"
                   aria-expanded="false">
                    <span id="span_user_name">？？？</span>
                    <span class="caret"></span>
                </a>

                <ul class="dropdown-menu">
                    <li><a href="#">个人信息</a></li>
                    <li><a href="javascript:logoutSubmit()">注销</a></li>
                </ul>
            </li>
        </ul>
    </div>
</nav>

<div class="container-fluid" id="app">
    <div class="row">
        <div class="col-xs-8 col-xs-push-2">
            <h4 class="title">收货人信息</h4>
            <p id="pp" class="alert alert-danger">
                <input type="hidden" id="takeDeliveryAddressId" v-model="defalutTakeDeliveryAddressId">
                <span style="font-weight: 800;">{{defaultName}}</span>
                <span class="mgl30">{{defaultDetail}}</span>
                <span class="mgl30">{{defaultPhone}}</span>
            </p>
            <a data-toggle="collapse" href="#moreAddress">更多地址</a>

            <div class="collapse"  id="moreAddress" style="margin-top: 15px;">
                <table id="allAddressTable" class="table">
                    <tr v-for="addr in allAddresses">
                        <td style="width: 100px;">
                            {{addr.name}} <span class="label label-success" v-if="addr.status == 1">默认</span>
                        </td>
                        <td style="width: 250px;">{{addr.detail}}</td>
                        <td style="width: 100px;">{{addr.phone}}</td>
                        <td style="width: 150px;">
                            <a href="javascript: void(0);" :aid="addr.id" onclick="setTakeDeliveryAddress(this)">设为收货地址</a>
                            <a href="javascript: void(0);" :aid="addr.id" onclick="setDefaultAddress(this)">设为默认</a>
                        </td>
                        <td style="width: 130px;">
                            <a href="javascript: void(0);" :aid="addr.id" onclick="updateAddress(this)">修改</a>
                            <a href="javascript: void(0);" :aid="addr.id" onclick="deleteAddress(this)">删除</a>
                        </td>
                    </tr>
                </table>
                <button type="button" onclick="addAddress()" class="btn btn-success">添加地址</button>
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-xs-8 col-xs-push-2">
            <h4 class="title">送货清单</h4>
            <table class="table">
                <thead>
                <tr>
                    <td>商品</td>
                    <td>单价</td>
                    <td>数量</td>
                </tr>
                </thead>
                <tbody >
                <tr v-for="g in goods">
                    <td style="max-width: 200px;">
                        <div class="media">
                            <div class="media-left">
                                <a href="javascript: void(0);">
                                    <img class="media-object" height="80px" width="62px" :src="g.imageSrc">
                                </a>
                            </div>
                            <div class="media-body">
                                <h4 class="media-heading">{{g.title}}</h4>
                            </div>
                        </div>
                    </td>
                    <td>{{g.price}}</td>
                    <td>{{g.num}}</td>
                </tr>
                </tbody>
                <tfoot>
                <tr v-if="goods.length != 0" style="text-align: right;">
                    <td colspan="5">
                        总计：￥{{totalPrice}} <button onclick="ensureOrder()" class="btn btn-danger">确认订单</button>
                    </td>
                </tr>
                </tfoot>
            </table>
        </div>
    </div>
</div>

<%--支付模态框--%>
<div class="modal" id="payModal" data-backdrop="static">
    <div class="modal-dialog" style="margin-top: 120px;">
        <div class="modal-content">
            <div class="modal-header">
                <button onclick="destoryPayModal()" class="close">
                    <span>&times;</span>
                </button>
                <h3 class="modal-title">支付信息</h3>
            </div>
            <div class="modal-body">
                <input type="hidden" id="orderNo">
                <h4 style="font-weight: 800;"><span>应付金额: </span>￥<span style="color: red;" id="totalPrice"></span></h4>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-danger" onclick="destoryPayModal()">取消支付</button>
                <button type="button" onclick="confirmPay()" class="btn btn-success">确认支付</button>
            </div>
        </div>
    </div>
</div>

<%--修改地址模态框--%>
<div class="modal fade" id="addressModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content" id="update_form">
            <div class="modal-header">
                <h4 class="modal-title" id="myModalLabel">添加/修改地址</h4>
            </div>
            <div class="modal-body">
                <div class="panel-body">
                    <form action="javascript:return false;" method="post" enctype="multipart/form-data">
                        <div class="form-group">
                            <label for="nameInUpdate">收件人</label>
                            <input class="form-control" autocomplete="off" name="nameInUpdate" id="nameInUpdate">
                        </div>
                        <div class="form-group">
                            <label for="phoneInUpdate">手机号</label>
                            <input class="form-control" autocomplete="off" name="phoneInUpdate" id="phoneInUpdate">
                        </div>
                        <div class="form-group">
                            <label for="detailInUpdate">详细地址</label>
                            <select id="province" onchange="initCity()">
                                <option value="-1">请选择省份</option>
                                <option :value="p.id" v-for="p in province">{{p.name}}</option>
                            </select>
                            城市:
                            <select id="city" onchange="initDistrict()">
                                <option value="-1">请选择城市</option>
                                <option :value="c.id" v-for="c in city">{{c.name}}</option>
                            </select>
                            地区:
                            <select id="district">
                                <option value="-1">请选择区镇</option>
                                <option v-for="d in district">{{d.name}}</option>
                            </select>
                            <input class="form-control" name="detailInUpdate" id="detailInUpdate">
                        </div>
                    </form>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-danger" onclick="closeAddressModal()">取消</button>
                <button id="confirmAddressBtn" type="button" onclick="confirmAddress(this)" class="btn btn-success">确认</button>
            </div>
        </div>
    </div>
</div>

</body>
<script>

    //显示用户登陆信息
    function initUserInfo() {
        if (!$.cookie('frontedUsername') || $.cookie('frontedUsername')=="null") {
            //用户未登录，显示登录和注册按钮
            $("#li_login").show();
            $("#li_register").show();
            $("#li_user_info").hide();
        } else {
            //用户已登录，显示用户名
            $("#li_login").hide();
            $("#li_register").hide();
            $("#li_user_info").show();
            $("#span_user_name").html($.cookie('frontedUsername'));
        }
    }
    initUserInfo();

    //注销点击事件
    function logoutSubmit() {
        //去后台删除cookie和session
        $.ajax({
            url: '${pageContext.servletContext.contextPath}/logout',
            type: 'get',
            dataType: 'json',
            success:function(_data) {
                $.removeCookie('frontedUsername')
                localStorage.removeItem('local_shopping_cart')
                location.href = "index.jsp"
            }
        })
    }

    var vm = new Vue({
        el: '#app',
        data: {
            defalutTakeDeliveryAddressId: 0,
            defaultDetail: '',    //默认详情信息
            defaultName: '',       //默认的名字
            defaultPhone: '',      // 默认电话
            allAddresses: [],     //其他的地址信息
            goods: [],
            totalPrice: 0
        }
    })

    var vmAddress = new Vue({
        el: '#addressModal',
        data: {
            address:{},
            province:[],
            city:[],
            district:[]
        }
    })
    //关闭地址模态框
    function closeAddressModal() {
        //清空地址信息
        $("#nameInUpdate").val('')
        $("#phoneInUpdate").val('')
        $("#detailInUpdate").val('')
        $("#confirmAddressBtn").removeAttr('aid');

        $("#city option[value='-1']").text('请选择城市');
        $("#district option[value='-1']").text('请选择地区');

        $("#province option[value='-1']").attr("selected", true);
        $("#city option[value='-1']").attr("selected", true);
        $("#district option[value='-1']").attr("selected", true);

        initCity();
        initDistrict()

        $('#addressModal').modal('hide');
    }
    //添加地址
    function addAddress(aTag) {
        $('#addressModal').modal('show');
        initProvince();
    }
    //修改地址
    function updateAddress(aTag) {
        initProvince();
        $('#addressModal').modal('show');
        //回显地址信息
        let aid = $(aTag).attr('aid');
        $.ajax({
            url: '${pageContext.servletContext.contextPath}/addressServlet',
            type: 'get',
            dataType: 'json',
            data: {method:"getAddressByAid",aid:aid},
            success:function(_data) {
                let split = _data.detail.split(' ');
                let province = split[0];
                let city = split[1];
                let district = split[2];
                let detail = split[3];
                //回显选择地址
                $("#province option[value='-1']").attr("selected", false);
                $("#province").find("option:contains(" + province + ")").attr("selected", true)

                initCity();
                // $("#city option[value='-1']").attr("selected", false);
                // $("#city").find("option:contains(" + city + ")").attr("selected", true);
                let cityTemp = $("#city option[value='-1']").text(city);
                $("#city option[value='205']").text(city);

                initDistrictByCityName(city);
                $("#district option[value='-1']").text(district);
                // initDistrict();
                // $("#district option[value='-1']").attr("selected", false);
                // $("#district").find("option:contains(" + district + ")").attr("selected", true);

                //回显地址
                $("#nameInUpdate").val(_data.name)
                $("#phoneInUpdate").val(_data.phone)
                $("#detailInUpdate").val(detail)
                $("#confirmAddressBtn").attr('aid',_data.id)
            }
        })
    }

    //延时函数
    var sleep = function(time) {
        var startTime = new Date().getTime() + parseInt(time, 10);
        while(new Date().getTime() < startTime) {}
    };
    //确认地址
    function confirmAddress(aTag) {
        //验证收件人
        let isName = validateName();
        //验证手机号
        let isPhone = validatePhone();
        if (!isName || !isPhone) {
            console.log(false)
            return;
        }

        let aid = $(aTag).attr('aid');
        let name = $("#nameInUpdate").val();
        let phone = $("#phoneInUpdate").val();
        //地址拼接
        let province = $("#province option:selected").text();
        let city = $("#city option:selected").text();
        let district = $("#district option:selected").text();
        let detail = province +' '+ city + ' ' + district + ' ' + $("#detailInUpdate").val();

        let state = 0;
        $.ajax({
            url: '${pageContext.servletContext.contextPath}/addressServlet',
            type: 'post',
            dataType: 'json',
            data: {method:"addOrUpdateAddress",name:name,phone:phone,detail:detail,state:state,aid:aid},
            success:function(_data) {
                alert(_data)
                closeAddressModal();
                //刷新地址页面
                getAddress();
            }
        })
    }
    //删除地址
    function deleteAddress(aTag) {
        if (confirm("是否删除该地址?")) {
            let aid = $(aTag).attr('aid');
            $.ajax({
                url: '${pageContext.servletContext.contextPath}/addressServlet',
                type: 'get',
                dataType: 'json',
                data: {method:"deleteAddress",aid:aid},
                success:function(_data) {
                    //刷新地址页面
                    getAddress()
                }
            })
        }
    }

    // 获取地址
    function getAddress() {
        $.ajax({
            url: '${pageContext.servletContext.contextPath}/addressServlet',
            type: 'get',
            data: {method: 'getAddressOfUser'},
            dataType: 'json',
            success: function(_data) {
                vm.allAddresses = [];
                for(var i = 0; i < _data.length; i++) {
                    var addr = _data[i];  //取到每个地址
                    vm.allAddresses.push(addr);
                    if(addr.takeDeliveryStatus == 1) {  // 收货地址
                        vm.defalutTakeDeliveryAddressId = addr.id; //设置默认收货地址的id
                        vm.defaultDetail = addr.detail;
                        vm.defaultName = addr.name;
                        vm.defaultPhone = addr.phone;
                    }
                    $("#defaultAddress").removeAttr('checked');
                }
            }
        })
    }

    function getGoodsInfo() {
        // 转换为json数据: {'1001': 1, '1002': 2}
        var localShoppingCart = JSON.parse(localStorage.getItem('local_shopping_cart'));
        var goodIds = Object.keys(localShoppingCart); //取到所有的商品的id, 返回值为数组：['1001', '1002']

        // join(‘,’) 只用指定的字符将数组拼接成字符串
        var goodIdsStr = goodIds.join(','); // ['1001', '1002', '1003'] -> 1001,1002,1003

        $.ajax({
            url: '${pageContext.servletContext.contextPath}/cart',
            type: 'get',
            dataType: 'json',
            data: {ids: goodIdsStr},
            success:function(_data) {  // [{}, {}, {}]
                var totalPrice = 0;
                for(var i = 0; i < _data.length; i++) {
                    var good = _data[i];  //获取到每件商品
                    var goodId = good.goodId; //获取商品的id, 目的是获取商品的数量
                    // 动态的添加的属性, 购买的商品数量
                    good.num = localShoppingCart['' + goodId];

                    totalPrice += (good.num * good.price); //计算总的价格
                    vm.goods.push(good);
                }
                vm.totalPrice = totalPrice;
            }
        })
    }

    getAddress();  //获取收货地址
    getGoodsInfo(); //获取商品信息

    //设置当前地址为收货地址
    function setTakeDeliveryAddress(aTag) {
        var currentAddressId = $(aTag).attr('aid'); //获取当前地址的id

        $.ajax({
            url: '${pageContext.servletContext.contextPath}/addressServlet',
            data: {addressId: currentAddressId, method: 'changeTakeDeliveryAddress'},
            dataType: 'json',
            type: 'get',
            success: function (_data) {
                if(_data.code > 0) {  //更新收货地址成功
                    getAddress();  //重新获取地址信息
                }else {
                    console.log(_data.msg)
                }
            }
        })
    }

    //设置当前地址为默认地址
    function setDefaultAddress(aTag) {
        var currentAddressId = $(aTag).attr('aid'); //获取当前地址的id

        $.ajax({
            url: '${pageContext.servletContext.contextPath}/addressServlet',
            data: {addressId: currentAddressId, method: 'changeDefaultAddress'},
            dataType: 'json',
            type: 'get',
            success: function (_data) {
                if(_data.code > 0) {  //更新收货地址成功
                    getAddress();  //重新获取地址信息
                }else {
                    console.log(_data.msg)
                }
            }
        })
    }

    // 点击 "确认订单"，去支付
    function ensureOrder() {
        var localShoppingCartData = localStorage.getItem('local_shopping_cart'); // {1001: 2, 1002:1}
        var defalutTakeDeliveryAddressId = $('#takeDeliveryAddressId').val();

        /**
         * 1. 将所有的商品生产订单。
         * 2. 展示模态框开始支付。
         */
        $.ajax({
            url: '${pageContext.servletContext.contextPath}/order',
            type: 'post',
            dataType: 'json',
            data: {goodsInfo: localShoppingCartData, takeDelivertyAddressId: defalutTakeDeliveryAddressId, method: 'ensureOrder'},
            success: function(_data) {
                // 生成订单成功
                if(_data.code > 0) {
                    // 删除用户的本地购物车数据
                    localStorage.removeItem('local_shopping_cart');
                    $('#totalPrice').html(_data.obj.totalPrice);
                    $('#orderNo').val(_data.obj.orderNo);
                    $('#payModal').modal('show');
                }else {
                    showErrorBox(_data.msg);
                }
            }
        })
    }

    // 确认支付, 总金额要从后台这边查询，将订单id传入到后台
    function confirmPay() {
        var orderNo = $('#orderNo').val(); //获取订单编号
        //将订单编号存在localStorage,跳转到支付页面
        localStorage.setItem('local_shopping_orderNo', orderNo.toString());
        location.href = "pay.jsp";
    }

    // 关闭支付模态框
    function destoryPayModal() {
        $('#payModal').modal('hide');
        location.href = 'showOrder.jsp';
    }

    // 显示错误提示信息
    function showErrorBox(msgText) {
        Lobibox.notify('warning', {
            size: 'mini',
            delay: 2000,
            delayIndicator: false,
            title: false, //不给title
            msg: msgText,
            sound: false  // 不要音频
        })
    }

    //添加地址验证
    function validateName() {
        var name = $('#nameInUpdate').val();  //获取用户名的值
        if(!name || "" == name.trim()) {
            showErrorBox('收件人不能为空.')
            return false;
        }
        return true;
    }

    function validatePhone() {
        var phone = $('#phoneInUpdate').val(); //获取手机号

        var reg = /^1(44|47|91|99|73|76|77|[358]\d)\d{8}$/;
        if(!reg.test(phone)) {
            showErrorBox('请填写正确手机号码.')
            return false;
        }
        return true;
    }

    //省份三级联动
    function initProvince() {
        //1.请求路径
        let url = "${pageContext.servletContext.contextPath}/selectAddress"
        //2.请求参数
        let params = {
            method: "getProvince"
        };
        //3.get请求
        $.ajax({
            url: url,
            async: false,
            data: params,
            type: 'get',
            dataType: 'json',
            success: function(_data) {
                for (let i = 0; i < _data.length; i++) {
                    vmAddress.province.push(_data[i])
                }
            }
        })
    }

    function initCity() {
        //0.初始化城市列表
        $("#city option[value='-1']").text('请选择城市');
        $("#district option[value='-1']").text('请选择地区');
        $("#city > option:gt(0)").remove()
        $("#district > option:gt(0)").remove()
        //1.请求路径
        let url = "${pageContext.servletContext.contextPath}/selectAddress"
        //2.请求参数
        let selectedProvinceId = $("#province option:selected").val();
        let params = {
            method: "getCity",
            provinceId: selectedProvinceId
        };
        //3.get请求
        $.ajax({
            url: url,
            async: false,
            data: params,
            type: 'get',
            dataType: 'json',
            success: function(_data) {
                for (let i = 0; i < _data.length; i++) {
                    vmAddress.city.push(_data[i])
                }
            }
        })
    }

    function initDistrictByCityName(cityName) {
        //0.初始化区镇列表
        $("#district option[value='-1']").text('请选择地区');
        $("#district > option:gt(0)").remove()
        //1.请求路径
        let url = "${pageContext.servletContext.contextPath}/selectAddress"
        //2.请求参数
        let selectedCityId = $("#city option:selected").val();
        let params = {
            method: "getDistrictByCityName",
            cityName: cityName
        };
        //3.get请求
        $.get(url, params, function (_data) {
            for (let i = 0; i < _data.length; i++) {
                vmAddress.district.push(_data[i])
            }
        },'json');
    }

    function initDistrict() {
        //0.初始化区镇列表
        $("#district > option:gt(0)").remove()
        //1.请求路径
        let url = "${pageContext.servletContext.contextPath}/selectAddress"
        //2.请求参数
        let selectedCityId = $("#city option:selected").val();
        let params = {
            method: "getDistrict",
            cityId: selectedCityId
        };
        //3.get请求
        $.ajax({
            url: url,
            async: false,
            data: params,
            type: 'get',
            dataType: 'json',
            success: function(_data) {
                for (let i = 0; i < _data.length; i++) {
                    vmAddress.district.push(_data[i])
                }
            }
        })
    }
</script>
</html>